package com.itheima.server.service;

import com.itheima.dubbo.api.UserInfoApi;
import com.itheima.server.exception.BusinessException;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;


    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     *
     * 更新用户的头像
     * @param headPhoto 用户的头像
     * @param id 用户的id
     */
    public void updateHeader(MultipartFile headPhoto, Long id) throws IOException {
        //1. 把照片上传到阿里云平台
        String imgUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        //2. 识别是否为人脸,如果不是人脸抛出异常
        if(!aipFaceTemplate.detect(imgUrl)){
            throw  new BusinessException("没法识别，请重新上传");
        }
        //3. 构建UserInfo的对象，设置id与图片的路径
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(imgUrl);

        //4. 更新用户信息
        userInfoApi.update(userInfo);

    }

    /**
     * 根据id查找用户的信息
     * @param userID  用户id
     * @return
     */
    public UserInfoVo findById(Long userID) {
        //1.查询用户的信息对象
        UserInfo userInfo =  userInfoApi.findById(userID);
       //2.把用户的信息对象封装到UserINfoVo对象中
        UserInfoVo userInfoVo = new UserInfoVo();
        //3. 属性拷贝
        BeanUtils.copyProperties(userInfo,userInfoVo);

        if(userInfo.getAge()!=null){
            userInfoVo.setAge(userInfo.getAge()+"");
        }
        return userInfoVo;
    }

    /**
     * 更新用户信息
     * @param userInfo
     */
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}
